import util from './util.js'
/**
 * 供外部post请求调用
 */
function post(url, params, onStart, onSuccess, onFailed) {
    request(url, params, "POST", onStart, onSuccess, onFailed);
}

/**
 * 供外部get请求调用
 */
function get(url, params, onStart, onSuccess, onFailed) {
    request(url, params, "GET", onStart, onSuccess, onFailed);
}

function upload(url, filePath, formData, onStart, onSuccess, onFailed) {
    onStart();
    wx.uploadFile({
        url: url,
        filePath: filePath,
        name: 'file',
        formData: formData,
        header: { 'content-type': 'multipart/form-data' },
        success: function (response) {
            const res = JSON.parse(response.data);
            if (res.data) {
                /** start 根据需求 接口的返回状态码进行处理 */
                if (res.status === 0) {
                    onSuccess(res); //request success
                } else {
                    onFailed(res.data); //request failed
                }
                /** end 处理结束*/
            }
        },
        fail: function (error) {
            console.log(error);
            util.showToast('加载失败');
        }
    })
}

/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式：GET/POST
 * @onStart 开始请求,初始加载loading等处理
 * @onSuccess 成功回调
 * @onFailed  失败回调
 */
function request(url, params, method, onStart, onSuccess, onFailed) {
    onStart(); //request start
    wx.request({
        url: url,
        data: dealParams(params),
        method: method,
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: function (res) {
            if (res.data) {
                /** start 根据需求 接口的返回状态码进行处理 */
                if (res.data.status === 0) {
                    onSuccess(res.data); //request success
                } else if (res.data.status === 1001) {
                    wx.reLaunch({
                        url: '/pages/login/login'
                    });
                } else {
                    onFailed(res.data); //request failed
                }
                /** end 处理结束*/
            } else {
                util.showToast('加载失败');
            }
        },
        fail: function (error) {
            console.log(error);
            util.showToast('加载失败');
        }
    })
}

/**
 * function: 根据需求处理请求参数：添加固定参数配置等
 * @params 请求参数
 */
function dealParams(params) {
    const prime = params;
    const file = {
        ...prime,
        xfjtk: wx.getStorageSync('xfjtk')
    }
    return file;
}

module.exports = {
    p: post,
    g: get,
    u: upload,
}